// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var leftMenu = require("../leftMenu/leftMenu");
	var topMenu = require("../topMenu/topMenu");
	var footer = require("../footer/footer_main");
	var router = require("../hash/pageRouter");
	var dialog = require("dialog");
	var validate = require("validate");
	var tools = require("tools");
	var databind = require("databind");
	var css_insurance = require("./createInsurance.css");
	var financeId;
	var insuranceId;
	var init = function(page) {
		financeId = page.params.financeId;
		insuranceId = page.params.insuranceId;

		footer.init();
		$("#footer").removeClass("none");
		leftMenu.init(8);
		topMenu.init(6);
		router.init();
		$(".table-section").removeClass("none");
		$(".footer").removeClass("none");
		tools.loadList("inquireFinanceApplicationDetail.json", $("#createInsuranceBody"), $("#createInsuranceTpl"), {
			financeId: financeId
		}, function() {
			tools.inquireCommonSelectorByStringList(15, $("#createInsurance .insuranceCompany"));
		});
		tools.loadList("inquireBulkstockInventoryPageList.json", $("#createInsuranceBulkstockListingBody"), $("#createInsuranceBulkstockListingTpl"), {
			financeId: financeId
		}, function() {

		});
		tools.requireInput($("#createInsurance"));
		if (insuranceId != null) {
			databind.fillInput1($("#createInsurance"), {
				action: "inquireInsuranceDetail.json?insuranceId=" + insuranceId
			}, function() {
				var fs = $("#insuranceFileUuid").val();
				$("#createInsurance .fs").html("");
				$.each(fs.split(','), function() {
					var _this = this;
					if (_this != "") {
						var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + _this + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + _this + '" class="showProductIntro">' + tools.inquireFile(_this) + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>';
						$("#createInsurance .fs").append(str);
					}
				});
			});
		}
		initEvent();
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			location.href = "../login/login.html";
		}

		$("#createInsurance").on("change", "#insuranceAttach", function() {
			uploadFile();
		});

		$("#createInsurance").on("click", ".deleteProductIntro", function() {
			$(this).parent().remove();
			var fs = "";
			$.each($(".mas"), function(i, v) {
				if (fs == "") {
					fs = $(v).attr("fileUuid");
				} else {
					fs = fs + ',' + $(v).attr("fileUuid");
				}
			});
			$("#insuranceFileUuid").val(fs);
		});

		$("#createInsurance").on("change", ".mold", function() {
			judgeMold($(this).val(), $("#createInsurance .applicantDepartment"), $("#createInsurance .applicantId"));
		});

		//下一步
		$("#createInsuranceNext").unbind("click").click(function() {

			if (insuranceId != null) {
				$("#createInsurance").attr("action", "updateInsurance");
				databind.fillForm($("#createInsurance"), {
					insuranceId: insuranceId
				});
				databind.submitDom($("#createInsurance"), function(data) {
					base.alert(1, "保存成功！");
					router.route("insuranceManage/selectInsuranceVariety.html?insuranceId=" + insuranceId + "&financeId=" + financeId);
				});
			} else {
				$("#createInsurance").attr("action", "createInsurance");
				databind.submitDom($("#createInsurance"), function(data) {
					base.alert(1, "保存成功！");
					router.route("insuranceManage/selectInsuranceVariety.html?insuranceId=" + data.datas[0].insuranceId + "&financeId=" + financeId);
				});
			}
		});
	};

	var judgeMold = function(type, company, companyId) {
		type = parseInt(type);
		switch (type) {
			case 1:
				$(company).val("平台");
				$(companyId).val("");
				$(company).attr("readonly", "readonly");
				break;
			case 2:
				$(company).val("");
				$(company).removeAttr("readonly");
				$(companyId).val("");
				logisticsAutoComplete($(company), $(companyId));
				break;
			case 3:
				$(company).removeAttr("readonly");
				$(company).val("");
				$(companyId).val("");
				enterpriseAutoComplete($(company), $(companyId));
				break;
			case 4:
				$(company).removeAttr("readonly");
				$(company).val("");
				$(companyId).val("");
				$(company).val("");
				break;
			default:
				break;
		}
	}

	//上传文件
	var uploadFile = function() {
		if ($("#insuranceAttach").val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: 'insuranceAttach',
				dataType: 'json',
				success: function(data) {
					var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + data.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.data[0].fileUuid + '" class="showProductIntro">' + data.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>'
					$(".insuranceAttach").before(str);

					var fs = "";
					$.each($(".mas"), function(i, v) {
						if (fs == "") {
							fs = $(v).attr("fileUuid");
						} else {
							fs = fs + ',' + $(v).attr("fileUuid");
						}
					});
					$("#insuranceFileUuid").val(fs);
				},
				complete: function(xml) {
					$("#insuranceAttach").change(function() {
						uploadFile();
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	};

	//物流公司自动补全
	var logisticsAutoComplete = function(dom, dom1) {
		//自动补全
		$(dom).autocomplete(seajs.data.handler + "inquireLogisticsCompanyList.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: true,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 1000,
				appKey: base.getData("appKey"),
				sessionUuid: base.getData("sid"),
				companyName: function() {
					return $(dom).val();
				}
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.companyName, //此处无需把全部列列出来，只是两个关键列
						result: row.companyName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($(dom).hasClass('nonemorelist')) {
					$(dom).removeClass('nonemorelist');
					return;
				};
				return "<table><tr><td>" + data.companyName + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.companyName;
			},
			formatResult: function(data, value) {
				return data.companyName;
			}
		}).result(function(event, data, formatted) { //回调
			if ($(dom).hasClass('nonemorelist')) {
				$(dom).removeClass('nonemorelist');
			} else {
				$(dom).addClass('nonemorelist');
			};
			$(dom1).val(data.companyId);
		});
	};

	//企业自动补全
	var enterpriseAutoComplete = function(dom, dom1) {
		//自动补全
		$(dom).autocomplete(seajs.data.handler + "inquireEnterprisePageList.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: true,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 1000,
				appKey: base.getData("appKey"),
				sessionUuid: base.getData("sid"),
				enterpriseName: function() {
					return $(dom).val();
				}
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.enterpriseName, //此处无需把全部列列出来，只是两个关键列
						result: row.enterpriseName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($(dom).hasClass('nonemorelist')) {
					$(dom).removeClass('nonemorelist');
					return;
				};
				return "<table><tr><td>" + data.enterpriseName + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.enterpriseName;
			},
			formatResult: function(data, value) {
				return data.enterpriseName;
			}
		}).result(function(event, data, formatted) { //回调
			if ($(dom).hasClass('nonemorelist')) {
				$(dom).removeClass('nonemorelist');
			} else {
				$(dom).addClass('nonemorelist');
			};
			$(dom1).val(data.enterpriseId);
		});
	};

	return {
		init: init
	};
});